import React, { useEffect, useState } from 'react';
import { Button, DatePicker, Input, Select } from 'antd';

import { isSuccess } from '@/utils/request';
import { download } from '@/utils/utils';
import { SearchInput } from '@/components/UserForm';
import { useRequest, defaultFormatResult } from '@/hooks';

import { queryEmployeeList } from '@/services/salaryManage/salaryCommon';
import { orgService } from '@/services/salaryManage/orgService';
import { commonService } from '@/services/salaryManage/statistics';
import Search from '@/pages/SalaryManage/components/SuperSearch';
import TwoColHead from '@/pages/SalaryManage/components/TwoColHead';
import AllGradeSelector from '@/pages/SalaryManage/components/AllGradeSelector';
import AllSelectPost from '@/pages/SalaryManage/components/AllSelectPost';
import AllOrganizationSelect from '@/pages/SalaryManage/components/AllOrganizationSelect';
import AllSelectDuty from '@/pages/SalaryManage/components/AllSelectDuty';
import useExportExcel from '@/pages/SalaryManage/Statistics/hooks/useExportExcel';

const { RangePicker } = DatePicker;
const SelectPoster = React.forwardRef(AllSelectPost);

const MONTH_FORMAT = 'YYYY-MM';

/**
 * 搜索控件
 * @returns {JSX.Element}
 * @constructor
 */
const SearchWrapper = ({
    form,
    searchModel,
    onSearch,
    dispatch,
    DISPATCH_TYPE,
    generateSearchModel,
    wrappedFormRef,
    organizationCode,
    isMoreExportType
}) => {
    const { getFieldDecorator } = form;
    wrappedFormRef(form);

    const [mode, setMode] = useState(['month', 'month']);
    const [period, setPeriod] = useState([undefined, undefined]);
    const [periodChanged, setPeriodChanged] = useState(false);
    const [periodClear, setPeriodClear] = useState(false);
    const { data: salaryNodeList } = useRequest(commonService.querySalaryNode, { ...defaultFormatResult });

    const handleOnSearch = () => {
        const searchValues = { ...form.getFieldsValue(), period };
        onSearch(searchValues);
    };

    const handlePeriodOpenChange = status => {
        if (!status && periodChanged) {
            // 不立即搜索
            // handleOnSearch();
        }
    };
    const handlePeriodChange = valueArray => {
        dispatch({
            type: DISPATCH_TYPE.setMultiStoreType,
            payload: {
                searchModel: generateSearchModel({ ...searchModel, period: valueArray })
            }
        });
        if (valueArray.length === 0) {
            setPeriodClear(true);
        }
    };

    const handlePeriodPanelChange = (valueArray, selectMode) => {
        dispatch({
            type: DISPATCH_TYPE.setMultiStoreType,
            payload: {
                searchModel: generateSearchModel({ ...searchModel, period: valueArray })
            }
        });
        setMode([
            selectMode[0] === 'date' ? 'month' : selectMode[0],
            selectMode[1] === 'date' ? 'month' : selectMode[1]
        ]);
        setPeriodChanged(true);
    };

    const { openModal, render: excelModelRender } = useExportExcel(
        dispatch,
        DISPATCH_TYPE,
        searchModel.salaryNode || 1
    );

    // Excel导出
    const excelExport = () => {
        if (isMoreExportType) {
            openModal();
        } else {
            download({
                getData: () => dispatch({ type: DISPATCH_TYPE.excelExportType })
            });
        }
    };

    useEffect(() => {
        if (periodClear) {
            handleOnSearch();
            setPeriodClear(false);
        }
    }, [periodClear]);

    useEffect(() => {
        if (period !== searchModel.period) {
            setPeriod(searchModel.period);
        }
    }, [searchModel.period]);

    return (
        <Search.Wrapper onSearch={() => onSearch(handleOnSearch)}>
            <TwoColHead
                left={
                    <Search.Commonly>
                        <Search.Item label="月份区间">
                            <RangePicker
                                value={period}
                                mode={mode}
                                format={MONTH_FORMAT}
                                onChange={handlePeriodChange}
                                onPanelChange={handlePeriodPanelChange}
                                style={{ width: '200px' }}
                                onOpenChange={handlePeriodOpenChange}
                            />
                            {getFieldDecorator('period', { initialValue: period })(<Input type="hidden" />)}
                        </Search.Item>
                        <Search.Item label="薪资节点">
                            {getFieldDecorator('salaryNode', {
                                initialValue: salaryNodeList?.[0]?.key
                            })(
                                <Select style={{ width: '120px' }}>
                                    {salaryNodeList
                                        ? salaryNodeList.map(item => (
                                              // eslint-disable-next-line react/jsx-indent
                                              <Select.Option value={item.key} key={item.key}>
                                                  {item.value}
                                              </Select.Option>
                                          ))
                                        : null}
                                </Select>
                            )}
                        </Search.Item>
                    </Search.Commonly>
                }
                right={
                    <>
                        <Button type="primary" onClick={excelExport}>
                            Excel导出
                        </Button>
                        {excelModelRender()}
                    </>
                }
                rightStyle={{ justifyContent: 'flex-start' }}
            />
            <Search.More>
                <Search.Item label="入职时间">
                    {getFieldDecorator('v_entryDate')(<RangePicker placeholder="开始时间-结束时间" />)}
                </Search.Item>
                <Search.Item label="姓名">
                    <span>
                        {getFieldDecorator('employeeCodeList')(
                            <SearchInput
                                params={{
                                    organizationCode
                                }}
                                getData={async params => {
                                    if (!params.organizationCode) {
                                        return [];
                                    }
                                    const employeeResponse = await queryEmployeeList({
                                        organizationCode: params.organizationCode
                                    });
                                    return isSuccess(employeeResponse) ? employeeResponse.data || [] : [];
                                }}
                                selectProps={{
                                    placeholder: '请输入员工姓名',
                                    allowClear: true,
                                    mode: 'multiple',
                                    maxTagCount: 2
                                }}
                                fieldsName={{
                                    value: 'employeeCode',
                                    title: 'name'
                                }}
                                style={{ width: '12.875em' }}
                            />
                        )}
                    </span>
                </Search.Item>

                <Search.Item label="组织机构">
                    {getFieldDecorator('departmentCodeList', { initialValue: undefined })(
                        <AllOrganizationSelect
                            treeCheckable
                            isFunctional
                            isStrictly
                            strictlyOutType="string"
                            maxTagCount={2}
                            extraQuery={{ auditStatus: 2 }}
                        />
                    )}
                </Search.Item>

                <Search.Item label="岗位">
                    {getFieldDecorator(
                        'dutyCodeList',
                        {}
                    )(
                        <AllSelectDuty
                            dataSource={() => orgService.queryDutyList()}
                            showSearch
                            maxTagCount={1}
                            mode="multiple"
                            placeholder="请选择岗位"
                        />
                    )}
                </Search.Item>
                <Search.Item label="职位">
                    {getFieldDecorator('positionCodeList')(
                        <SelectPoster
                            showSearch
                            placeholder="请选择职位"
                            getPopupContainer={trigger => trigger.parentNode}
                            dropdownStyle={{
                                maxHeight: '30vh',
                                overflow: 'auto'
                            }}
                            allowClear
                            treeCheckable
                            maxTagCount={2}
                        />
                    )}
                </Search.Item>
                <Search.Item label="职级">
                    {getFieldDecorator('rankCodeList', {})(<AllGradeSelector mode="multiple" maxTagCount={2} />)}
                </Search.Item>
            </Search.More>
        </Search.Wrapper>
    );
};

export default SearchWrapper;
